<template>
  <div class="page-mobile-member-card">
    <white-header
      :isShowTopNav="true"
      :isShowBack="true"
      :isShowRight="true"
      title="卡号兑换"
    ></white-header>
    <div class="card-box">
      <div class="study-card">
        <!-- <img src="/img/mobile/study-card.png" alt=""> -->
        <div class="study-card-title">兑换会员</div>
        <div class="card-input">
          <input
            type="text"
            class="card-number"
            placeholder="请输入卡密"
            v-model="card_account"
          />
        </div>
        <div class="card-btn">
          <div class="activation" @touchstart="activeCard()">兑换</div>
        </div>
      </div>
    </div>
    <div class="card-list">
      <div class="count-list-title">
        已兑换卡券（<span class="count">{{ activation_record.total }}</span
        >）
      </div>
      <div
        class="list-item"
        v-for="(item, index) in activation_record_list"
        :key="index"
      >
        <div class="card-name">
          {{ item.codeName ? item.codeName : "未知" }}
        </div>
        <div class="card-num">卡密：{{ item.code }}</div>
        <div class="card-num">兑换时间：{{ formatDate(item.useTime) }}</div>
        <img class="right-icon" src="/img/mobile/right-icon.png" alt="" />
      </div>
      <!-- <div class="list-item">
        <div class="card-name">UI设计师-全链路全面培养计划</div>
        <div class="card-num">卡号：54891689161989-5656</div>
        <img class="right-icon" src="/img/mobile/right-icon.png" alt="">
      </div> -->
    </div>
    <div class="footer" v-show="activation_record_list.length != 0">
      <span class="tips">我是有底线的</span>
    </div>
    <van-empty
      description="暂时没有记录哟~"
      v-show="activation_record_list.length == 0"
    />
  </div>
</template>

<script>
import { cardActivate } from "~/api/account/wallet";
import { exchangeMember, getExchangeMemberList } from "~/api/member";
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
import { mapState, mapActions, mapMutations } from "vuex";
export default {
  props: ["setDisabled", "refreshFun", "setLoading"],
  components: {
    WhiteHeader
  },
  data() {
    return {
      card_account: "", //激活码
      activation_record_list: [], //卡卷激活记录
      activation_record: {
        page: 1,
        pageSize: 10,
        total: 0
      }
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      token(state) {
        return state.token;
      },
      is_ios(state) {
        return state.is_ios;
      },
      is_in_wechat(state) {
        return state.is_in_wechat;
      },
      is_in_minigram(state) {
        return state.is_in_minigram;
      },
      is_loading(state) {
        return state.is_loading;
      },
      is_wechat_ios_limit(state) {
        return state.is_wechat_ios_limit;
      }
    }),
    is_show_price() {
      if (this.is_wechat_ios_limit) {
        return this.is_ios && this.is_in_wechat;
      } else {
        return false;
      }
    },
    is_allow() {
      if (!this.recharge_num) {
        return false;
      } else {
        return true;
      }
    },
    active_query() {
      return this.$route.query.active;
    },
    num() {
      return this.$route.query.num;
    },
    redirect_url() {
      return this.$route.query.rdurl;
    }
  },
  watch: {},
  destroyed() {
    window.removeEventListener("scroll", this.eventListener);
    this.setDisabled(true);
  },
  deactivated() {
    window.removeEventListener("scroll", this.eventListener);
    this.setDisabled(true);
  },
  activated() {
    if (process.client) {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        this.$router.replace("/m/login");
      }
      window.addEventListener("scroll", this.eventListener);
    }
    this.activation_record = {
      page: 1,
      pageSize: 10,
      total: 0
    };
    this.getActivationRecordListFun();
    this.setDisabled(false);
    this.refreshFun(() => {
      this.activation_record = {
        page: 1,
        pageSize: 10,
        total: 0
      };
      this.getActivationRecordListFun();
      this.setLoading(false);
    });
  },
  methods: {
    ...mapActions([]),
    ...mapMutations(["SET_IS_LOADING"]),
    formatDate(date) {
      var date = new Date(date);
      var YY = date.getFullYear() + "-";
      var MM =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var hh =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var mm =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      var ss =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return YY + MM + DD + " " + hh + mm + ss;
    },
    async getActivationRecordListFun(fetch_type) {
      this.SET_IS_LOADING(true);
      const { page, pageSize, total } = this.activation_record;
      let params = {
        userId: this.user_info.id,
        sort: "id desc",
        offset: pageSize * (page - 1),
        limit: pageSize
      };
      let result = await getExchangeMemberList(params);
      console.log("result:", result);
      if (result && result.data && result.data.code == 200) {
        if (fetch_type == "pullup") {
          this.activation_record_list = [
            ...this.activation_record_list,
            ...result.data.data.rows
          ];
        } else {
          this.activation_record_list = result.data.data.rows;
        }
        this.activation_record.total = result.data.data.total;
        this.SET_IS_LOADING(false);
      } else {
        this.SET_IS_LOADING(false);
        this.$Message.error(this.$t("locale.pc.personal.t124"));
      }
    },
    async activeCard() {
      if (!this.card_account) {
        this.$toast("卡密为空");
        return false;
      }
      this.SET_IS_LOADING(true);
      let params = {
        userId: this.user_info.id,
        code: this.card_account.trim()
      };
      let result = await exchangeMember(params);
      console.log("兑换码：", result);
      if (result && result.data && result.data.code == 200) {
        this.SET_IS_LOADING(false);
        this.$toast("兑换成功");
        this.card_account = "";
        this.activation_record = {
          page: 1,
          pageSize: 10,
          total: 0
        };
        this.getActivationRecordListFun();
      } else {
        this.SET_IS_LOADING(false);
        this.$toast("激活失败，" + result.data.msg);
      }
    },
    pullUp() {
      // 滚动条离顶部的距离
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      // 窗口可视区域高度
      let clientHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      // 滚动区域高度
      let scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;
      // 滚动条 + 可视区域高度 >= 滚动条高度 ==>  滚动条触底
      if (scrollTop + clientHeight >= scrollHeight - 120) {
        console.log("上拉加载");
        if (
          this.activation_record.total <= this.activation_record_list.length
        ) {
          return;
        }
        if (this.is_loading) {
          return;
        }
        this.activation_record.page++;
        this.getActivationRecordListFun("pullup");
      }
    },
    eventListener() {
      this.throttle(this.pullUp, 30);
    },
    throttle(fn, delay) {
      let lastTime = 0;
      return !(function() {
        let nowTime = Date.now();
        if (nowTime - lastTime > delay) {
          fn.call(this);
          lastTime = nowTime;
        }
      })();
    }
  },
  created() {
    if (process.client) {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        return this.$router.replace("/m/login");
      }
    }
    this.activation_record = {
      page: 1,
      pageSize: 10,
      total: 0
    };
    // this.getActivationRecordListFun();
    this.setDisabled(false);
    this.refreshFun(() => {
      this.activation_record = {
        page: 1,
        pageSize: 10,
        total: 0
      };
      this.getActivationRecordListFun();
      this.setLoading(false);
    });
  },
  mounted() {
    if (process.client) {
      window.addEventListener("scroll", this.eventListener);
    }
  }
};
</script>

<style lang="scss" scoped>
.page-mobile-member-card {
  width: 100vw;
  min-height: 100vh;
  background-color: #ffffff;
  .footer {
    padding: 0.3rem;
    font-size: 0.26rem;
    color: #babec2;
    text-align: center;
    .tips {
      position: relative;
    }
    .tips::before {
      content: "";
      display: block;
      position: absolute;
      left: -1.7rem;
      top: 50%;
      transform: translateY(-1px);
      width: 1.5rem;
      height: 1px;
      background: #babec2;
    }
    .tips::after {
      content: "";
      display: block;
      position: absolute;
      right: -1.7rem;
      top: 50%;
      width: 1.5rem;
      transform: translateY(-1px);
      height: 1px;
      background: #babec2;
    }
  }
  .card-box {
    padding: 0.3rem 0;
    // border-top: 0.026rem solid #f7f7fa;
    .study-card {
      width: 6.624rem;
      height: 3.456rem;
      background-color: #d19a47;
      background-image: url("/img/mobile/study-card.png");
      background-size: 100% 100%;
      background-repeat: no-repeat;
      margin: 0 auto;
      border-radius: 0.192rem;
      padding: 0.4rem 0.26rem 0.26rem 0.4rem;
      position: relative;
      .study-card-title {
        color: #ffffff;
        font-size: 0.3072rem;
        font-weight: bold;
      }
      .card-input {
        .card-number {
          margin-top: 0.6rem;
          width: 5.76rem;
          height: 0.63rem;
          font-size: 0.3rem;
          // line-height: .63rem;
          border: 0.01rem solid #dfe2e5;
          border-radius: 0.315rem;
          background: #ffffff;
          padding: 0 0.3rem;
        }
      }
      .card-btn {
        margin-top: 0.3rem;
        display: flex;
        justify-content: flex-end;
        padding-right: 0.2rem;
        .activation {
          width: 1.248rem;
          height: 0.5184rem;
          background-color: #ffffff;
          font-size: 0.3rem;
          font-weight: bold;
          border-radius: 0.2592rem;
          text-align: center;
          line-height: 0.5184rem;
          color: #d19a47;
        }
      }
      img {
        width: 6.624rem;
        height: 3.456rem;
        position: absolute;
        background-color: #d19a47;
        left: 0;
        top: 0;
      }
    }
  }
  .card-list {
    padding: 0.3rem 0;
    width: 100%;
    .count-list-title {
      padding-left: 0.26rem;
      color: #313233;
      font-size: 0.3rem;
      height: 1rem;
      line-height: 1rem;
      font-weight: bold;
      border-bottom: 0.026rem solid #ededf1;
      .count {
        margin: 0 0.1rem;
        color: #d19a47;
      }
    }
    .list-item {
      width: 100%;
      //   height: 1.632rem;
      height: 2rem;
      box-sizing: border-box;
      padding: 0.3rem;
      border-bottom: 0.026rem solid #ededf1;
      position: relative;
      .right-icon {
        position: absolute;
        right: 0.4rem;
        top: 50%;
        transform: translateY(-50%);
        display: block;
        width: 0.2304rem;
        height: 0.2304rem;
      }
      .card-name {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #4a4b4d;
        font-size: 0.288rem;
        line-height: 0.5rem;
      }
      .card-num {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #adb0b3;
        font-size: 0.24rem;
        line-height: 0.5rem;
      }
    }
    .list-item:last-child {
      border: none;
    }
  }
}
</style>
<style lang="scss">
.page-mobile-member-card {
}
</style>
